
<template>
  <el-dialog :model-value ="true" :title="props.title" width="500px" @close="handleCancel">
    <el-form :model="form" label-width="120px" :rules="rules" ref="formRef">
      <el-form-item label="海报类型名称" prop="posterTypeName">
        <el-input v-model="form.posterTypeName" placeholder="请输入海报类型名称" clearable />
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="handleCancel">取消</el-button>
      <el-button type="primary" @click="handleSubmit">确定</el-button>
    </template>
  </el-dialog>
</template>
<script setup lang="ts">
import { on } from 'events';
import { ref ,watch,onMounted } from 'vue'
import { ElMessage } from 'element-plus'

const props =withDefaults(defineProps<{
  title?: string,
  currentObj?: any,
  posterList?: any[]
}>(), {
  title: '新增海报类型',
  currentObj: ()=>({}),
  posterList: ()=>([])
})
const emits = defineEmits<{
  (emitStr: 'ok', emitData: any): void;
  (emitStr: 'cancel'): void
}>()
const form = ref({
  posterTypeName: '',
})

const formRef = ref<any>(null)

// watch(()=>props.currentObj, (newVal) => {
//   console.log('newVal++++', newVal)
//   if(newVal){
//     form.value.posterTypeName = newVal.name
//   }
// },
// )

const rules = ref({
  posterTypeName: [
    { required: true, message: '请输入海报类型', trigger: 'blur' },
    { max: 20, message: '字数不能超过20个字', trigger: 'blur' },
  ]
})
const handleSubmit = async () => {
  // 确保posterList是一个数组再进行查找操作
  if(Array.isArray(props.posterList) && props.posterList.find((item: any) => item.name === form.value.posterTypeName)){
    ElMessage.warning('海报类型名称已存在')
    return
  }
  if (!formRef.value) return
  await formRef.value.validate(async (valid, fields) => {
    if (valid) {
      emits('ok', form.value)
    }else{
      console.log('error submit!!', fields)
    }
  })
}
const handleCancel = () => {
  emits('cancel')
}
 onMounted(() => {
  console.log('props.currentObj++++', props.currentObj)
  if(props.currentObj){
    form.value.posterTypeName = props.currentObj.name
    console.log('form.value.posterTypeName++++', form.value.posterTypeName)
  }
 })
</script>
<style scoped lang="scss">

</style>